import { Form, Input, message, Modal } from 'antd'
import React, { useEffect, useState } from 'react'
import style from './index.module.scss'

export default function index({ isShow, setIsShow, mode, titleList, addApi, changeApi, goSearch, method, id }) {
  const [form] = Form.useForm()

  const cancel = () => {
    setIsShow()
    form.resetFields()
  }

  // 获取结果
  const getResult = (obj, msg) => {
    if (obj.code === 2000) {
      setIsShow()
      // setSuccessChange()
      goSearch()
      message.success(msg)
    } else {
      message.error(`${mode === 'change' ? '修改失败' : '添加失败'},服务器返回结果为：${obj.msg}`)
    }
  }

  // 发起提交
  const submit = async values => {
    if (mode === 'add') {
      const res = await addApi(values)
      const resObj = await res.json()
      getResult(resObj, '添加成功')
    } else {
      const res = await changeApi(values)
      const resObj = await res.json()
      getResult(resObj, '修改成功')
    }
  }

  // const [list, setList] = useState({})
  // useEffect(() => {
  //   ; (async () => {
  //     const res = await method(id)
  //     const resObj = await res.json()
  //     console.log(resObj)
  //     setList(resObj.data || {})
  //     // form.setFieldsValue(resObj.data || {}); // 设置初始值
  //   })()
  // }, [id])
  const handleAfterOpen = async () => {
    if (mode === 'update' && id) {
      try {
        const res = await method(id);
        const resObj = await res.json();
        if (resObj.data) {
          form.setFieldsValue(resObj.data);
        }
      } catch (error) {
        console.error("Failed to fetch data:", error);
        message.error("获取数据失败");
      }
    } else {
      form.resetFields();
    }
  };

  return (
    <Modal afterOpenChange={handleAfterOpen} title={mode === 'add' ? '添加' : '修改'} okText={mode === 'add' ? '确认添加' : '确认修改'} open={isShow} onCancel={cancel} cancelText="取消"
      okButtonProps={{
        autoFocus: true,
        htmlType: 'submit',
      }}
      modalRender={(dom) => (
        <Form
          form={form}
          name="form_in_modal"
          onFinish={(values) => submit(values)}
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
        >
          {dom}
        </Form>
      )}
    >
      {titleList.map(item => (
        <Form.Item
          style={{ width: '100%' }}
          className={style['row-style']}
          key={item.dataIndex}
          colon={false}
          label={<span className={style['title-style']}>{item.title}</span>}
          name={item.dataIndex}
          rules={[
            {
              required: true,
              message: `请输入${item.title}`,
            },
          ]}
        >
          <Input className={style['data-style']} placeholder={`请输入${item.title}`} />
        </Form.Item>
      ))}

    </Modal>
  )
}
